package com.servlet.user;

import com.dao.UserDao;
import com.entity.User;
import com.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author admin
 */
@WebServlet(name = "UserAddServlet",urlPatterns = "/UserAddServlet.filter")
public class UserAddServlet extends HttpServlet {
//    private String encoding;


    private User user = null;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("UserAddServlet");
        String u_name = request.getParameter("u_name");
        String u_pwd = request.getParameter("u_pwd");
        String u_age = request.getParameter("u_age");
        String u_sex = request.getParameter("u_sex");
        user.setU_name(u_name);
        user.setU_pwd(u_pwd);
        user.setU_age(Integer.getInteger(u_age));
        user.setU_sex(Integer.getInteger(u_sex));
        assert u_sex != null;
        SqlSession session = MybatisUtil.getSession();
        UserDao userDao = session.getMapper(UserDao.class);
        if(userDao.selectUser(user)){
            userDao.insertUser(user);
            System.out.println("用户添加成功");
            response.sendRedirect(request.getContextPath()+"/UserSelectAllServlet.filter");
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
